//
//  UIViewController+LogClassName.m
//  ios-loan
//
//  Created by guoqingping on 2017/12/15.
//  Copyright © 2017年 hxhg. All rights reserved.
//

#import "UIViewController+LogClassName.h"
#import <objc/runtime.h>

typedef void (* _VIMP)(id, SEL, ...);

@implementation UIViewController (LogClassName)

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        // get system viewDidLoad method
        Method viewDidLoad = class_getInstanceMethod(self, @selector(viewDidLoad));
        
        // get the system implementation of viewDidLoad
        _VIMP viewDidLoad_VIMP = (_VIMP)method_getImplementation(viewDidLoad);
        
        // resetter the  system implementation of viewDidLoad
        method_setImplementation(viewDidLoad, imp_implementationWithBlock(^ (id target , SEL action){
            
            // the system viewDidLoad method
            viewDidLoad_VIMP(target , @selector(viewDidLoad));
            
            
            // the new add NSLog method
            NSLog(@"%@ did load",target);
        }));
        
        
    });
}



+ (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

+ (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}

@end
